<?php

namespace app\model;

use think\Model;

class OperationLog extends Model
{
    protected $name = 'operation_logs';
    
    // 设置字段信息
    protected $schema = [
        'id' => 'int',
        'user_id' => 'int',
        'username' => 'string',
        'action' => 'string',
        'module' => 'string',
        'description' => 'text',
        'request_method' => 'string',
        'request_url' => 'string',
        'request_params' => 'text',
        'response_code' => 'int',
        'response_message' => 'string',
        'ip_address' => 'string',
        'user_agent' => 'string',
        'execution_time' => 'decimal',
        'status' => 'string',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];

    // 自动时间戳
    protected $autoWriteTimestamp = true;
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';

    // 类型转换
    protected $type = [
        'user_id' => 'integer',
        'response_code' => 'integer',
        'execution_time' => 'float',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];

    /**
     * 记录操作日志
     * @param array $data 日志数据
     * @return bool
     */
    public static function record($data)
    {
        try {
            $log = new self();
            $log->save($data);
            return true;
        } catch (\Exception $e) {
            // 记录日志失败时，写入系统日志
            error_log('Operation log save failed: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * 获取日志列表
     * @param array $params 查询参数
     * @return array
     */
    public static function getLogList($params = [])
    {
        $query = self::order('created_at', 'desc');

        // 用户筛选
        if (!empty($params['user_id'])) {
            $query->where('user_id', $params['user_id']);
        }

        // 模块筛选
        if (!empty($params['module'])) {
            $query->where('module', $params['module']);
        }

        // 操作筛选
        if (!empty($params['action'])) {
            $query->where('action', 'like', '%' . $params['action'] . '%');
        }

        // 状态筛选
        if (!empty($params['status'])) {
            $query->where('status', $params['status']);
        }

        // 时间范围筛选
        if (!empty($params['start_date'])) {
            $query->where('created_at', '>=', $params['start_date']);
        }
        if (!empty($params['end_date'])) {
            $query->where('created_at', '<=', $params['end_date'] . ' 23:59:59');
        }

        // 关键词搜索
        if (!empty($params['keyword'])) {
            $query->where(function ($q) use ($params) {
                $q->where('description', 'like', '%' . $params['keyword'] . '%')
                  ->whereOr('request_url', 'like', '%' . $params['keyword'] . '%')
                  ->whereOr('username', 'like', '%' . $params['keyword'] . '%');
            });
        }

        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 20;

        $total = $query->count();
        $list = $query->page($page, $limit)->select();

        return [
            'total' => $total,
            'list' => $list,
            'page' => $page,
            'limit' => $limit
        ];
    }

    /**
     * 获取模块统计
     * @return array
     */
    public static function getModuleStats()
    {
        return self::field('module, count(*) as count')
            ->group('module')
            ->order('count', 'desc')
            ->select()
            ->toArray();
    }

    /**
     * 获取状态统计
     * @return array
     */
    public static function getStatusStats()
    {
        return self::field('status, count(*) as count')
            ->group('status')
            ->select()
            ->toArray();
    }

    /**
     * 清理旧日志
     * @param int $days 保留天数
     * @return int
     */
    public static function cleanOldLogs($days = 30)
    {
        $date = date('Y-m-d H:i:s', strtotime("-{$days} days"));
        return self::where('created_at', '<', $date)->delete();
    }
} 